<template>
    <el-card>
        <template #header>
            <h3>居民账号信息</h3>
        </template>
        <el-button class="add" type="primary" @click="showAddWindow()">添加居民账号</el-button>
        <!-- 搜索区域 -->
        <el-form inline>
            <!-- <el-form-item label="ID" style="width: 100px">
                <el-input v-model="params.user_id"></el-input>
            </el-form-item> -->
            <el-form-item label="账号" style="width: 200px">
                <el-input v-model="params.account"></el-input>
            </el-form-item>
            <el-form-item label="姓名" style="width: 200px">
                <el-input v-model="params.name"></el-input>
            </el-form-item>
            <!-- <el-form-item label="邮箱" style="width: 200px">
                <el-input v-model="params.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" style="width: 200px">
                <el-input v-model="params.phone"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="身份证号" style="width: 230px">
                <el-input v-model="params.id_card"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="性别">
                <el-select v-model="params.gender" placeholder="" style="width: 90px">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="年龄">
                <el-input v-model="params.age"></el-input>
            </el-form-item>
            <el-form-item label="住址">
                <el-input v-model="params.address"></el-input>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" @click="searchResidents()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="resident" border @sort-change="handleSortChange">
            <el-table-column label="账号" prop="account" sortable="custom" align="center"></el-table-column>
            <el-table-column label="姓名" prop="name" sortable="custom" align="center"></el-table-column>
            <el-table-column label="邮箱" prop="email" sortable="custom" align="center">
                <template #default="scope">
                    <span v-if="scope.row.email">
                        <!-- 邮箱脱敏处理 -->
                        {{ scope.row.email.slice(0, 3) + '****' + scope.row.email.slice(scope.row.email.indexOf('@')) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="电话" prop="phone" sortable="custom" align="center">
                <template #default="scope">
                    <span v-if="scope.row.phone">
                        <!-- 电话号码脱敏处理 -->
                        {{ scope.row.phone.slice(0, 3) + '****' + scope.row.phone.slice(scope.row.phone.length - 4) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="身份证号" prop="id_card" sortable="custom" align="center">
                <template #default="scope">
                    <span v-if="scope.row.id_card">
                        <!-- 身份证号脱敏处理 -->
                        {{ scope.row.id_card.slice(0, 6) + '****' + scope.row.id_card.slice(scope.row.id_card.length -
                            4) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="280" align="center">
                <template #default="scope">
                    <!-- 重置密码确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认重置该居民账号的密码吗？">
                        <template #reference>
                            <el-button type="warning">重置密码</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="warning" size="small" @click.once="resetPassword(scope.row, confirm)">
                                确认
                                <!-- resetPassword(scope.row) -->
                            </el-button>
                        </template>
                    </el-popconfirm>
                    <!-- 删除确认气泡 -->
                    <el-popconfirm width="250" icon-color="#626AEF" title="确认删除该居民账号吗？">
                        <template #reference>
                            <el-button type="danger">删除</el-button>
                        </template>
                        <template #actions="{ confirm, cancel }">
                            <el-button size="small" @click.once="cancel">取消</el-button>
                            <el-button type="danger" size="small" @click.once="deleteResident(scope.row, confirm)">
                                确认
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 居民账号信息编辑弹窗 -->
    <el-dialog v-model="showEdit" title="居民账号信息" width="500" @close="closeWindow">
        <el-form :model="curResident" label-width="120px" :rules="rules" ref="curResidentForm">
            <!-- 上传头像 -->
            <el-form-item label="头像" prop="avatar" v-show="!showAdd">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:8082/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <el-avatar v-if="curResident.user_img" shape="circle" :size="150" :fit="'cover'"
                        :src="curResident.user_img" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="账号" prop="account">
                <el-input v-model="curResident.account" v-if="showAdd"></el-input>
                <el-input v-model="curResident.account" v-else disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="curResident.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-show="!showAdd">
                <el-input v-model="curResident.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="curResident.phone"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender" v-show="!showAdd">
                <el-radio-group v-model="curResident.gender">
                    <el-radio :value="0">女</el-radio>
                    <el-radio :value="1">男</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthdate" v-show="!showAdd">
                <el-date-picker v-model="curResident.birthdate" type="date" placeholder="选择您的出生日期"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="年龄" prop="age" v-show="!showAdd">
                <!-- 根据生日自动计算年龄 -->
                <el-input v-model="age" disabled></el-input>
            </el-form-item>
            <el-form-item label="住址" prop="address" v-show="!showAdd">
                <el-input v-model="curResident.address"></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="id_card" v-show="!showAdd">
                <el-input v-model="curResident.id_card"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="!showAdd" type="primary" @click="updateResident(curResident)">保存</el-button>
                <el-button v-if="showAdd" type="primary" @click="addResident(curResident)">添加</el-button>
                <el-button @click="showEdit = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { findResidentInfoAPI, residentInfoUpdateAPI } from '@/api/resident';
import { addUserAPI, deleteUserAPI, resetPasswordAPI } from '@/api/user';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                user_id: '',
                name: '',
                account: '',
                email: '',
                phone: '',
                gender: '',
                age: '',
                address: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            resident: [],
            statusOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: '0',
                    label: '女'
                },
                {
                    value: '1',
                    label: '男'
                }
            ],
            showEdit: false,
            showAdd: false,
            curResident: {
                email: '',
                phone: ''
            },
            rulesEdit: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                account: { required: true, message: '账号不能为空', trigger: 'blur' },
                email: [
                    { required: false, trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                            if (!this.showAdd && value !== '') {
                                if (emailRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的邮箱地址'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                id_card: [
                    { required: false, message: '身份证号码不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const idRegex = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                            if (value !== '') {
                                if (idRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的身份证号码'));
                                }
                            }
                        }
                    }
                ]
            },
            rulesAdd: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                account: { required: true, message: '账号不能为空', trigger: 'blur' },
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            rules: {}
        }
    },
    methods: {
        loadResidentInfoList() {
            findResidentInfoAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.resident = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        searchResidents() {
            this.loadResidentInfoList();
        },
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadResidentInfoList();
        },
        // 图片上传成功之后回调函数
        handleAvatarSuccess(response) {
            this.curResident.user_img = response;
        },
        showEditWindow(row) {
            this.curResident = JSON.parse(JSON.stringify(row));
            this.showEdit = true;
            this.rules = this.rulesEdit;
        },
        updateResident(row) {
            this.$refs.curResidentForm.validate((val) => {
                if (val) {
                    residentInfoUpdateAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadResidentInfoList();
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
            this.showEdit = false
        },
        resetPassword(row, confirm) {
            resetPasswordAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        deleteResident(row, confirm) {
            deleteUserAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadResidentInfoList();
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            confirm();
        },
        showAddWindow() {
            this.curResident = {};
            this.showEdit = true;
            this.showAdd = true;
            this.rules = this.rulesAdd;
        },
        addResident(row) {
            row.role = 0;
            this.$refs.curResidentForm.validate((val) => {
                if (val) {
                    addUserAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadResidentInfoList();
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
            this.showEdit = false;
            this.showAdd = false;
        },
        closeWindow() {
            this.loadResidentInfoList();
            this.showEdit = false;
            this.showAdd = false;
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                this.loadResidentInfoList();
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                this.loadResidentInfoList();
            }
        }
    },
    computed: {
        age() {
            if (this.curResident.birthdate == null) {
                return '选择出生日期计算年龄';
            }
            let birthDate = new Date(this.curResident.birthdate);
            let currentDate = new Date();
            let age = currentDate.getFullYear() - birthDate.getFullYear();
            let monthDifference = currentDate.getMonth() - birthDate.getMonth();
            if (monthDifference < 0 || (monthDifference === 0 && currentDate.getDate() < birthDate.getDate())) {
                age--;
            }
            this.curResident.age = age;
            if (age < 0 || age > 120) {
                return '出生日期不合理';
            }
            return age;
        }
    },
    created() {
        this.loadResidentInfoList();
    }
}
</script>

<style scoped>
.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.add {
    position: relative;
    top: -10px;
}
</style>